# from django.utils import timezone
# from datetime import datetime, timedelta
# import logging
# from borrowing.models import Borrowing, Book
# from django.http import JsonResponse
# from django.views import View
# import json
# import os
#
# logging.basicconfig(filename=os.path.join(os.getcwd(),'demo.log'),level=logging.DEBUG, filemode='a',
#                      format='%(asctime)s - %(process)s - %(levelname)s: %(message)s')
#
# LOGGER = logging.getLogger("demo")
#
# # 获取名为当前模块的日志记录器
# logger = logging.getLogger(__name__)
#
# # 查询图书
# class BookSet(View):
#     def get(self, request):
#         print("BookSet get---------------------")
#         books = Book.objects.filter(is_delete=False)  # 查询全部信息
#         books_data = []  # 创建一个列表
#         for book in books:
#             books_data.append({
#                 'id': book.id,
#                 'title': book.title,
#                 'author': book.author,
#                 'isbn': book.isbn,
#                 'published_date': book.published_date.strftime('%Y-%m-%d'),  # 格式化日期
#                 'available': book.available
#             })
#         return JsonResponse({'msg': '查询成功', 'books': books_data})
#
#     def post(self, request):
#         try:
#             data = json.loads(request.body)
#             book = Book.objects.create(
#                 title=data.get('title'),
#                 author=data.get('author'),
#                 isbn=data.get('isbn'),
#                 published_date=data.get('published_date'),
#                 available=data.get('available', True)  # 还书默认为true
#             )
#             return JsonResponse({'msg': '录入成功', 'book_id': book.id}, status=200)
#         except Exception as e:
#             return JsonResponse({'msg': f'录入失败: {e}'}, status=400)
#
#
# class BookPutAndDelete(View):
#     def put(self, request, id):
#         try:
#             book = Book.objects.get(id=id)  # 获取要修改的图书信息
#             data = json.loads(request.body)
#             if 'title' in data:
#                 book.title = data['title']
#             if 'author' in data:
#                 book.author = data['author']
#             if 'isbn' in data:
#                 book.isbn = data['isbn']
#             if 'published_date' in data:
#                 book.published_date = data['published_date']
#             if 'available' in data:
#                 book.available = data['available']
#             book.save()
#             return JsonResponse({'msg': '修改成功', 'book_id': book.id}, status=200)
#         except Exception as e:
#             return JsonResponse({'msg': f'修改失败: {e}'}, status=400)
#
#     def delete(self, request, id):
#         try:
#             book = Book.objects.get(id=id)
#             book.is_delete = True
#             book.save()
#             return JsonResponse({'msg': '销毁成功', 'code': 200}, status=200)
#         except Exception as e:
#             return JsonResponse({'msg': f'销毁失败: {e}'}, status=400)
#
#
# # 借书
# class BorrowingListView(View):
#     def post(self, request, id):
#         try:
#             book = Book.objects.get(id=id)
#         except Exception as e:
#             return JsonResponse({'msg': f'图书不存在{e}'}, status=400)
#         # if not book.available:
#         #     return JsonResponse({'msg': '图书已经被借了'}, status=400)
#         borrower = Borrowing(
#             user=request.user,
#             book=book,
#             due_date=timezone.now() + timezone.timedelta(days=30)
#         )
#         borrower.save()
#         book.available = False
#         book.save()
#         return JsonResponse({'msg': '图书借书成功'}, status=200)
#
#
# # 还书
# class BorrowingBookListView(View):
#     def post(self, request, id):
#         try:
#             book = Book.objects.get(id=id)
#         except Book.DoesNotExist:
#             return JsonResponse({'msg': '图书不存在'}, status=400)
#         try:
#             borrower = Borrowing.objects.get(book=book, user=request.user, returned=False)
#         except Borrowing.DoesNotExist:
#             return JsonResponse({'msg': "没有找到有效的借阅记录"},status=400)
#         borrower.available = True
#         borrower.save()
#         book.available = True
#         book.save()
#         return JsonResponse({'msg':'还书成功'}, status=200)


from django.utils import timezone
from datetime import datetime, timedelta
import logging
from borrowing.models import Borrowing, Book
from django.http import JsonResponse
from django.views import View
import json
import os

# 配置日志
logging.basicConfig(filename=os.path.join(os.getcwd(), 'demo.log'), level=logging.DEBUG, filemode='a',
                    format='%(asctime)s - %(process)s - %(levelname)s: %(message)s')

# 获取名为当前模块的日志记录器
logger = logging.getLogger(__name__)


# 查询图书
class BookSet(View):
    def get(self, request):
        logger.info("BookSet get 请求开始")
        try:
            print("BookSet get---------------------")
            books = Book.objects.filter(is_delete=False)  # 查询全部信息
            books_data = []  # 创建一个列表
            for book in books:
                books_data.append({
                    'id': book.id,
                    'title': book.title,
                    'author': book.author,
                    'isbn': book.isbn,
                    'published_date': book.published_date.strftime('%Y-%m-%d'),  # 格式化日期
                    'available': book.available
                })
            logger.info("BookSet get 请求成功，查询到 %d 本图书", len(books))
            return JsonResponse({'msg': '查询成功', 'books': books_data})
        except Exception as e:
            logger.error("BookSet get 请求失败: %s", str(e))
            return JsonResponse({'msg': f'查询失败: {e}'}, status=400)

    def post(self, request):
        logger.info("BookSet post 请求开始")
        try:
            data = json.loads(request.body)
            book = Book.objects.create(
                title=data.get('title'),
                author=data.get('author'),
                isbn=data.get('isbn'),
                published_date=data.get('published_date'),
                available=data.get('available', True)  # 还书默认为true
            )
            logger.info("BookSet post 请求成功，录入图书 ID 为 %d", book.id)
            return JsonResponse({'msg': '录入成功', 'book_id': book.id}, status=200)
        except Exception as e:
            logger.error("BookSet post 请求失败: %s", str(e))
            return JsonResponse({'msg': f'录入失败: {e}'}, status=400)


class BookPutAndDelete(View):
    def put(self, request, id):
        logger.info("BookPutAndDelete put 请求开始，图书 ID 为 %d", id)
        try:
            book = Book.objects.get(id=id)  # 获取要修改的图书信息
            data = json.loads(request.body)
            if 'title' in data:
                book.title = data['title']
            if 'author' in data:
                book.author = data['author']
            if 'isbn' in data:
                book.isbn = data['isbn']
            if 'published_date' in data:
                book.published_date = data['published_date']
            if 'available' in data:
                book.available = data['available']
            book.save()
            logger.info("BookPutAndDelete put 请求成功，修改图书 ID 为 %d", book.id)
            return JsonResponse({'msg': '修改成功', 'book_id': book.id}, status=200)
        except Exception as e:
            logger.error("BookPutAndDelete put 请求失败，图书 ID 为 %d: %s", id, str(e))
            return JsonResponse({'msg': f'修改失败: {e}'}, status=400)

    def delete(self, request, id):
        logger.info("BookPutAndDelete delete 请求开始，图书 ID 为 %d", id)
        try:
            book = Book.objects.get(id=id)
            book.is_delete = True
            book.save()
            logger.info("BookPutAndDelete delete 请求成功，销毁图书 ID 为 %d", book.id)
            return JsonResponse({'msg': '销毁成功', 'code': 200}, status=200)
        except Exception as e:
            logger.error("BookPutAndDelete delete 请求失败，图书 ID 为 %d: %s", id, str(e))
            return JsonResponse({'msg': f'销毁失败: {e}'}, status=400)


# 借书
class BorrowingListView(View):
    def post(self, request, id):
        logger.info("BorrowingListView post 请求开始，图书 ID 为 %d", id)
        try:
            book = Book.objects.get(id=id)
        except Exception as e:
            logger.error("BorrowingListView post 请求失败，图书 ID 为 %d: %s", id, str(e))
            return JsonResponse({'msg': f'图书不存在{e}'}, status=400)
        # if not book.available:
        #     return JsonResponse({'msg': '图书已经被借了'}, status=400)
        borrower = Borrowing(
            user=request.user,
            book=book,
            due_date=timezone.now() + timezone.timedelta(days=30)
        )
        borrower.save()
        book.available = False
        book.save()
        logger.info("BorrowingListView post 请求成功，用户 %s 借阅图书 ID 为 %d", request.user, id)
        return JsonResponse({'msg': '图书借书成功'}, status=200)


# 还书
class BorrowingBookListView(View):
    def post(self, request, id):
        logger.info("BorrowingBookListView post 请求开始，图书 ID 为 %d", id)
        try:
            book = Book.objects.get(id=id)
        except Book.DoesNotExist:
            logger.error("BorrowingBookListView post 请求失败，图书 ID 为 %d: 图书不存在", id)
            return JsonResponse({'msg': '图书不存在'}, status=400)
        try:
            borrower = Borrowing.objects.get(book=book, user=request.user, returned=False)
        except Borrowing.DoesNotExist:
            logger.error("BorrowingBookListView post 请求失败，图书 ID 为 %d: 没有找到有效的借阅记录", id)
            return JsonResponse({'msg': "没有找到有效的借阅记录"}, status=400)
        borrower.available = True
        borrower.save()
        book.available = True
        book.save()
        logger.info("BorrowingBookListView post 请求成功，用户 %s 归还图书 ID 为 %d", request.user, id)
        return JsonResponse({'msg': '还书成功'}, status=200)
